const express = require('express');
const { pool } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取所有费用数据（公开接口，供前端页面使用）
router.get('/', async (req, res) => {
    try {
        const [rows] = await pool.execute(
            'SELECT * FROM expenses ORDER BY created_at DESC'
        );
        res.json({
            success: true,
            data: rows
        });
    } catch (error) {
        console.error('获取费用数据错误:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 获取单个费用数据
router.get('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const [rows] = await pool.execute(
            'SELECT * FROM expenses WHERE id = ?',
            [id]
        );

        if (rows.length === 0) {
            return res.status(404).json({ success: false, message: '费用记录不存在' });
        }

        res.json({
            success: true,
            data: rows[0]
        });
    } catch (error) {
        console.error('获取费用数据错误:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 创建费用数据（需要认证）
router.post('/', authenticateToken, async (req, res) => {
    try {
        const { category, name, cost, trip } = req.body;

        if (!category || !name || !cost || !trip) {
            return res.status(400).json({ 
                success: false, 
                message: '类别、项目名称、金额和所属徒步不能为空' 
            });
        }

        if (isNaN(cost) || parseFloat(cost) < 0) {
            return res.status(400).json({ 
                success: false, 
                message: '金额必须是有效的正数' 
            });
        }

        const [result] = await pool.execute(
            'INSERT INTO expenses (category, name, cost, trip) VALUES (?, ?, ?, ?)',
            [category, name, parseFloat(cost), trip]
        );

        res.status(201).json({
            success: true,
            message: '费用记录创建成功',
            data: {
                id: result.insertId,
                category,
                name,
                cost: parseFloat(cost),
                trip
            }
        });
    } catch (error) {
        console.error('创建费用数据错误:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 更新费用数据（需要认证）
router.put('/:id', authenticateToken, async (req, res) => {
    try {
        const { id } = req.params;
        const { category, name, cost, trip } = req.body;

        if (!category || !name || !cost || !trip) {
            return res.status(400).json({ 
                success: false, 
                message: '类别、项目名称、金额和所属徒步不能为空' 
            });
        }

        if (isNaN(cost) || parseFloat(cost) < 0) {
            return res.status(400).json({ 
                success: false, 
                message: '金额必须是有效的正数' 
            });
        }

        const [result] = await pool.execute(
            'UPDATE expenses SET category = ?, name = ?, cost = ?, trip = ? WHERE id = ?',
            [category, name, parseFloat(cost), trip, id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ success: false, message: '费用记录不存在' });
        }

        res.json({
            success: true,
            message: '费用记录更新成功',
            data: {
                id: parseInt(id),
                category,
                name,
                cost: parseFloat(cost),
                trip
            }
        });
    } catch (error) {
        console.error('更新费用数据错误:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 删除费用数据（需要认证）
router.delete('/:id', authenticateToken, async (req, res) => {
    try {
        const { id } = req.params;

        const [result] = await pool.execute(
            'DELETE FROM expenses WHERE id = ?',
            [id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ success: false, message: '费用记录不存在' });
        }

        res.json({
            success: true,
            message: '费用记录删除成功'
        });
    } catch (error) {
        console.error('删除费用数据错误:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 获取费用统计数据
router.get('/stats/summary', async (req, res) => {
    try {
        // 总金额
        const [totalResult] = await pool.execute(
            'SELECT SUM(cost) as total FROM expenses'
        );

        // 按类别统计
        const [categoryStats] = await pool.execute(
            'SELECT category, SUM(cost) as total, COUNT(*) as count FROM expenses GROUP BY category ORDER BY total DESC'
        );

        // 按徒步统计
        const [tripStats] = await pool.execute(
            'SELECT trip, SUM(cost) as total, COUNT(*) as count FROM expenses GROUP BY trip ORDER BY total DESC'
        );

        res.json({
            success: true,
            data: {
                total: totalResult[0].total || 0,
                categoryStats,
                tripStats
            }
        });
    } catch (error) {
        console.error('获取统计数据错误:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

module.exports = router;